<template>
  <div class="agent" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other_half_hour" :query="query" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="agent_search">
                  <div class="skill">
                    <el-radio-group v-model="radio1"
                                    size = "mini"
                                    @change = "changeAgentBig">
                      <el-radio :label="1">{{$t('report.lookAgentWork')}}</el-radio>
                      <!--<el-radio :label="0">{{$t('report.lookSkillWork')}}</el-radio>-->
                    </el-radio-group></div>
                  <div class="wrap_conti" v-show="radio1">
                    <span class="chan_ag">{{$t('report.chooseAgent')}}:</span>
                    <el-radio-group v-model="radio3"
                                    size = "mini"
                                    @change = "changeAgent">
                      <div>
                        <el-radio :label="1">{{$t('public.checkAll')}}</el-radio></div>
                      <div class="skill">
                        <el-radio :label="2">{{$t('report.accordAgentChoose')}}</el-radio>
                        <!-- <el-select v-model="selectedAgentList"
                                   multiple
                                   filterable
                                   :disabled = "radio3 !== 2"
                                   size="mini"
                                   :placeholder="$t('report.pleChoseAgent')">
                          <el-option
                            v-for="item in agentOptions"
                            :label="item.label"
                            :value="item.value"
                            :key="item.value">
                          </el-option>
                        </el-select> -->
                        <m7Select :placeholder="$t('public.pickAgent')" :disabled = "radio3 !== 2" class="el-select" filterable multiple :options="selectAgents" v-model="selectedAgentList"></m7Select>
                        <el-checkbox :disabled = "radio3 !== 2"
                                     v-model.trim="query.includeSubordinate">
                          {{$t('public.includeSubordinate')}}</el-checkbox></div>
                      <div class="skill">
                        <el-radio :label="3">{{$t('report.chooseSkillAgent')}}</el-radio>
                        <el-select size="mini"
                                   v-model.trim="currentQueue"
                                   :placeholder="$t('report.queueNaSea')"
                                   multiple
                                   :disabled = "radio3 !== 3"
                                   filterable
                                   @change = "change">
                          <el-option v-for="item in mailQueues"
                                     :label="item.DisplayName"
                                     :value="item._id"
                                     :key="item._id"></el-option>
                        </el-select></div>
                    </el-radio-group>
                  </div>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab agent_table">
        <div class="export">
          <el-button class="primary_btn fr" v-on:click.stop="isHeaderConfigShow=!isHeaderConfigShow" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                {{$t('report.remoteTotalCount')}} <br>
                {{$t('report.remoteTotalTime')}} <br>
                {{$t('report.remoteAvgTime')}} <br>
                {{$t('report.remoteTotalPingjia')}} <br>
                {{$t('report.remoteParticipationRate')}} <br>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <checkbox-table :data="tableData" :sum="totalData" :config="headOptions.Config" @tellme = "reducteDate"> </checkbox-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <header-option v-show="isHeaderConfigShow" :show="isHeaderConfigShow" :option="headOptionsShow" :type="id" v-on:close="close"></header-option>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import headerOption from '../base/headerOption.vue'
  import checkboxTable from '../base/checkboxTable.vue'
  import { deepClone, getFormatTimeBySecond, optionTimeTypeCheck } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, checkTime, searchTime, colorConfigArr } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'remote_control_agent',
    data () {
      return {
        isFold: false,
        currentQueueS: '',
        radio3: 1,
        radio1: 1,
        noDealDate: [],
        currentQueue: [],
        mailQueues: [],
        id: 'remoteassist_report_agent',
        title: this.$t('report.remoteControlAgent'),
        loading: false,
        query: {includeSubordinate: false},
        dialogVisible: false,
        selectedAgentList: [],
        // selectedAgentListClone: [],
        agentOptions: [],
        serverData: [],
        isHeaderConfigShow: false,
        headOptions: { Config: [], data: [] },
        headOptionsShow: { Config: [], data: [] },
        highchartsDefaultOptions: {
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.remoteControlAgent') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      checkboxTable,
      headerOption
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
        }
        return  this.agentOptions
      },
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      tableData () {
        return this.getTableData(this.serverData, this.headOptions)
      },
      totalData () {
        return this.getTotalData(this.noDealDate, this.headOptions)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.noDealDate || this.noDealDate.length === 0) {
          return options
        }

        let headerConfig = this.headOptions.Config || []
        let datas = this.noDealDate
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'agentName') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          if (item.name === 'avgServerTime' || item.name === 'serverTime') {
            serie.tooltip = { valueSuffix: 's' }
          } else if (item.name === 'sessionCompleteRate' || item.name === 'sessionRollOutRate' || item.name === 'inviteSessionRate') {
            serie.tooltip = { valueSuffix: '%' }
          }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(this.getAgentName(datas[i].agentId))
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(datas[i][seriesArray[j].valueName])
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray
        return options
      }
    },
    methods: {
      getTableData (serverData, headOptions, isExport) {
        if (!serverData || serverData.length === 0) {
          return []
        }

        let data = deepClone(serverData)
        data.forEach(item => {
          if (isExport) {
            var {displayName, exten} = this.getAgentDisplayNameAndExten(item.agentId)
            item.agentName = displayName
            item.agentExten = exten
          } else {
            item.agentName = this.getAgentName(item.agentId)
          }

          headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getFormatTimeBySecond(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = Math.round(item[option.name]) + 's'
            }
          })
        })
        return data
      },
      getTotalData (noDealDate, headOptions) {
        if (!noDealDate || noDealDate.length === 0) {
          return [{agentName: this.$t('report.total')}]
        }

        let headerConfig = headOptions.Config || []
        let datas = noDealDate
        let total = {
          agentName: this.$t('report.total')
        }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }

            if (headerConfig[i].name === 'sessionAverageTimeLength') {
              total.sessionTotalTimeLength += datas[j]['sessionTotalTimeLength']
            } else if (headerConfig[i].name === 'averageFirstResponseTimeLength') {
              total.firstResponseTotalTimeLength += datas[j]['firstResponseTotalTimeLength']
            }
          }
        }

        // 平均解决时长
        total.avgServerTime = total.serverCount > 0 ? Math.round(total.serverTime / total.serverCount) : 0
        // 参评率
        total.evaluateOddsCount = total.serverCount > 0 ? ((total.evaluateCount / total.serverCount) * 100).toFixed(1) : 0
        total.evaluateOddsCount = total.evaluateOddsCount + '%'
        headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            total[option.name] = getFormatTimeBySecond(total[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            total[option.name] = total[option.name] + 's'
          }
        })
        return [total]
      },
      isShowFold (bool) {
        this.isFold = bool
      },
      changeAgentBig (num) {
        delete this.query.queryExten
        this.currentQueueS = ''
        this.selectedAgentList = []
        // this.selectedAgentListClone = []
        this.currentQueue = []
        this.includeSubordinate = false
      },
      changeSkill (id) {
        this.query.queryExten = id
      },
      reducteDate (data) {
        let dealDate = []
        data.map(item => {
          this.serverData.map(col => {
            if (item.agentId === col.agentId) {
              dealDate.push(col)
            }
          })
        })
        this.noDealDate = dealDate
      },
      changeAgent () {
        this.selectedAgentList = []
        this.currentQueue = []
        // this.selectedAgentListClone = []
      },
      change (peerIds) {
        // this.selectedAgentListClone = []
        this.selectedAgentList = []
        this.includeSubordinate = false
        if (peerIds.length === 0) {
          return
        }
        let agentIds = []
        peerIds.map((id) => {
          this.mailQueues.map((item) => {
            if (item._id === id) {
              agentIds = agentIds.concat(item.AssignMembers)
            }
          })
        })
        agentIds.map((obj) => {
          if (obj) {
            this.selectedAgentList.push(obj.agentID)
          }
        })
        this.selectedAgentList = Array.from(new Set(this.selectedAgentList))
      },
      getAgentName (id) {
        console.log(this.$store.getters.agents)
        let agent = this.$store.getters.agents[id]
        let getAgent = agent ? agent.displayName + '(' + agent.exten + ')' : ''
        return getAgent
      },
      getAgentDisplayNameAndExten (id) {
        let agent = this.$store.getters.agents[id]
        return {
          displayName: agent ? agent.displayName : '',
          exten: agent ? agent.exten : ''
        }
      },
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id },
          user: {
            type: this.$store.state.session.user.type,
            moduleUsers: this.$store.state.session.user.moduleUsers
          }
        }
        // 校验类型与时间
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, true, false)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAgentList.length > 0) {
          query.selectedAgentList = this.selectedAgentList.join(',')
        }
        if (this.currentQueue.length !== 0 && this.selectedAgentList.length === 0) {
          query.selectedAgentList = '000000'
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        var query = data.query
        this.loading = true
        this.$store.dispatch('queryRemoteControlAgentReport', data).then((res) => {
          //  图表标题 加入 定时段的 时间
          let highchartsTitle = ''
          if (query.timePeriod) {
            let timePeriodStartStr = query.timePeriodStart || '00:00'
            let timePeriodEndStr = query.timePeriodEnd || '23:59'
            highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
          }
          this.highchartsDefaultOptions.title.text = this.$t('report.remoteControlAgent') + highchartsTitle
          // 表头
          this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
          this.headOptionsShow = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptionsShow)
          this.serverData = deepClone(res.data) || this.serverData
          this.noDealDate = deepClone(res.data) || this.serverData
          this.loading = false
        })
      },
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryRemoteControlAgentReport', data).then((res) => {
          this.loading = false
          var serverData = deepClone(res.data) || []
          var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])
          var sum = []
          if (serverData.length !== 0) {
            sum = this.getTotalData(serverData, headOptions)
          }
          var tableData = this.getTableData(serverData, headOptions, true).concat(sum)

          var ConfigsTemp = []
          headOptions.Config && headOptions.Config.forEach(config => {
            ConfigsTemp.push(config)
            if (config.name === 'agentName') {
              ConfigsTemp.push({
                show: config.show,
                displayname: '工号',
                name: 'agentExten'
              })
            }
          })
          headOptions.Config = ConfigsTemp

          var headers = headOptionsToXlsxHeaders(headOptions.Config)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.callReportAgent') + timeStamp)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportRemoteAssistAgent',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, true, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAgentList.length > 0) {
          query.selectedAgentList = this.selectedAgentList.join(',')
        }
        if (this.currentQueue.length !== 0 && this.selectedAgentList.length === 0) {
          query.selectedAgentList = '000000'
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImAgentReport', data)
      },
      close (data) {
        if (data) {
          this.search()
        }
        this.isHeaderConfigShow = false
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.remoteControlAgent') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agentOptions = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
        this.search()
      })
      this.$store.dispatch('getDicCache', {type: 'mailQueues'}).then((res) => {
        if (res && res.success) {
          this.mailQueues = res.data
        }
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .agent
    .table
      padding-bottom: 20px
    .agent_search
      .wrap_conti
        margin 14px 0 0 0px
        .chan_ag
          float left
          margin-right 16px
        .el-radio
          margin-right 30px
    .skill
      margin-top 14px
      .el-select
        width 200px
      .ski
        margin-right 26px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 15px
      border-radius 50%
      margin 20px 0 0 6px
      .iconfont
        border none
        font-size 10px
        color $c-main
    .agen
      margin 14px 0 0px 18px
      .el-select
        width 220px
    .search
      margin-bottom 34px
      .el-checkbox
        margin-left 16px
    .age
      display inline-block
      height 36px
      line-height 36px
      margin-right 16px
</style>
